layui.use('form', function(){
	
	initEditor();
	
	var form = layui.form;
	
	//监听提交
	form.on('submit(myForm)', function(data){
		var json = data.field;
		var id = $("#id").val();
		var createDate = $("#createDate").val();
		var articleStatus = $("#articleStatus").val();
		if(id==undefined || id==null || id==""){
			delete json.id;
		}
		if(createDate==undefined || createDate==null || createDate==""){
			delete json.createDate;
		}
		if(articleStatus==undefined || articleStatus==null || articleStatus==""){
			delete json.articleStatus;
		}
		json.articleContentHtml = editor.getHTML();//获取编辑器html内容
		save(json);
		return false;
	});
	
	form.verify({
		articleName: function(value, item){ //value：表单的值、item：表单的DOM对象
			var go = checkNotNull(value, '文章名称');
			if(go==""){
				go = checkLength(value, 100, '文章名称');
				if(go!=""){					
					return go;
				}
			}else{
				return go;
			}
		}
	});

});

var editor;
//初始化markdown
function initEditor(){
	var articleContent = $("#articleContent").val();
	var articleContentHtml = $("#articleContentHtml").val();
	editor = editormd("articleContent-editor", {
		width  : "100%",
		height : "75%",
		saveHTMLToTextarea : true,
		emoji: true,
		htmlDecode : true,
		path : "/plugins/editormd/lib/",
		value: articleContent,
		markdown: articleContentHtml
	});
}

//不能为空
function checkNotNull(value, preTip){
	if(""==$.trim(value)){
		return preTip + '不能空';
	}
	return "";
}

//检查长度
function checkLength(value, maxSize, preTip){
	if(value.length>maxSize){
		return preTip + '不能超过' + maxSize + '个字符';
	}
	return "";
}

//保存
function save(json){
	$.ajax({
		type: 'post',
		url: '/base/article/save',
		dataType: 'json',
		data: json,
		success: function(result){
			var code = result.code;
			if(code==0){
				layui.layer.msg('保存成功', {icon: 6},function(){
					parent.refresh();
					toBack();//刷新表格
				});	
			}else{
				layui.layer.msg('保存失败', {icon: 5});
			}
		},
		error: function(e){
			layui.layer.msg('网络异常', {icon: 5});
		}
	});
}

//返回
function toBack(){
	var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
	parent.layer.close(index); //再执行关闭  
}